<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="800px"
    :close-on-click-modal="false"
    destroy-on-close
    class="chat-dialog"
  >
    <div class="chat-container">
      <!-- 左侧会话列表 -->
      <div class="session-list" v-if="showSessionList">
        <div class="session-header">
          <h3>聊天列表</h3>
        </div>
        <el-scrollbar>
          <div 
            v-for="session in sessions" 
            :key="session.id"
            class="session-item"
            :class="{ 
              active: currentSession?.id === session.id,
              'has-unread': session.unreadCount > 0 && session.lastSenderId !== userId && currentSession?.id !== session.id
            }"
          >
            <div class="session-content" @click="selectSession(session)">
              <el-avatar :size="40" :src="getSessionAvatar(session)">
                {{ getSessionName(session)?.charAt(0) || '?' }}
              </el-avatar>
              <div class="session-info">
                <div class="session-name">
                  {{ getSessionName(session) }}
                  <span v-if="session.unreadCount > 0 && session.lastSenderId !== userId" class="unread-indicator"></span>
                </div>
                <div class="last-message">
                  {{ session.lastMessage || '暂无消息' }}
                </div>
              </div>
              <el-badge 
                v-if="session.unreadCount > 0 && session.lastSenderId !== userId" 
                :value="session.unreadCount" 
                class="unread-badge"
              />
            </div>
            <div class="session-actions" v-if="!isStaff">
              <el-popconfirm
                title="确定要删除这个会话吗？"
                @confirm="deleteSession(session.id)"
                confirm-button-text="确定"
                cancel-button-text="取消"
              >
                <template #reference>
                  <el-icon class="delete-icon"><Delete /></el-icon>
                </template>
              </el-popconfirm>
            </div>
          </div>
        </el-scrollbar>
      </div>

      <!-- 右侧聊天区域 -->
      <div class="chat-main">
        <div class="chat-header">
          <span>{{ currentChatName }}</span>
          <div class="header-actions" v-if="messages.length && !isStaff && showSessionList">
            <el-button type="danger" size="small" @click="confirmClearMessages">
              清空聊天记录
            </el-button>
          </div>
        </div>
        
        <!-- 消息列表 -->
        <div class="message-list" ref="messageList">
          <el-scrollbar>
            <div class="messages-container">
              <div 
                v-for="msg in messages" 
                :key="msg.id"
                class="message-item"
                :class="{ 'message-mine': msg.senderId === userId }"
              >
                <el-avatar 
                  :size="36" 
                  :src="msg.senderId === userId ? userAvatar : targetAvatar"
                >
                  {{ msg.senderId === userId ? (userName?.charAt(0) || '?') : (targetName?.charAt(0) || '?') }}
                </el-avatar>
                <div class="message-content">
                  <div class="message-text">{{ msg.content }}</div>
                  <div class="message-time">
                    {{ formatTime(msg.createTime) }}
                    <el-popconfirm
                      v-if="msg.senderId === userId"
                      title="确定要删除这条消息吗？"
                      @confirm="deleteMessage(msg.id)"
                      confirm-button-text="确定"
                      cancel-button-text="取消"
                    >
                      <template #reference>
                        <el-icon class="delete-icon"><Delete /></el-icon>
                      </template>
                    </el-popconfirm>
                  </div>
                </div>
              </div>
            </div>
          </el-scrollbar>
        </div>

        <!-- 输入区域 -->
        <div class="chat-input">
          <el-input
            v-model="inputMessage"
            type="textarea"
            :rows="3"
            placeholder="请输入消息"
            @keyup.enter="sendMessage"
            @keydown.enter.prevent
          />
          <el-button type="primary" @click="sendMessage">发送</el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { useUserStore } from '@/store/user'
import { formatDate } from '@/utils/dateUtils'
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'

const props = defineProps({
  modelValue: Boolean,
  targetId: {
    type: [String, Number],
    default: null
  },
  showSessionList: {
    type: Boolean,
    default: true
  }
})

const emit = defineEmits(['update:modelValue'])

const userStore = useUserStore()
const userId = computed(() => userStore.userInfo?.id)
const userName = computed(() => userStore.userInfo?.name || userStore.userInfo?.username)
const userAvatar = computed(() => {
  const avatar = userStore.userInfo?.avatar
  return avatar ? (avatar.startsWith('http') ? avatar : `/api${avatar}`) : ''
})

// 聊天相关数据
const sessions = ref([])
const currentSession = ref(null)
const messages = ref([])
const inputMessage = ref('')
const ws = ref(null)
const messageList = ref(null)

// 计算属性
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const title = computed(() => props.showSessionList ? '消息中心' : '在线咨询')

const currentChatName = computed(() => {
  if (!currentSession.value) return ''
  return getSessionName(currentSession.value)
})

const targetName = computed(() => {
  if (!currentSession.value) return ''
  return userStore.userInfo?.roleCode === 'STAFF' 
    ? currentSession.value.user?.name 
    : currentSession.value.staff?.user?.name
})

const targetAvatar = computed(() => {
  if (!currentSession.value) return ''
  if (userStore.userInfo?.roleCode === 'STAFF') {
    const avatar = currentSession.value.user?.avatar
    return avatar ? (avatar.startsWith('http') ? avatar : `/api${avatar}`) : ''
  } else {
    // 普通用户看到服务人员头像
    const avatar = currentSession.value.staff?.user?.avatar
    return avatar ? (avatar.startsWith('http') ? avatar : `/api${avatar}`) : ''
  }
})

// 添加一个计算属性来判断当前用户是否是服务人员
const isStaff = computed(() => userStore.userInfo?.roleCode === 'STAFF')

// 方法
const getSessionName = (session) => {
  if (!session) return '未知用户';
  
  if (userStore.userInfo?.roleCode === 'STAFF') {
    return session.user?.name || session.user?.username || '未知用户1';
  } else {
    return session.staff?.user?.name || session.staff?.user?.username || '未知用户2';
  }
}

const getSessionAvatar = (session) => {
  if (!session) return '';
  if (userStore.userInfo?.roleCode === 'STAFF') {
    const avatar = session.user?.avatar
    return avatar ? (avatar.startsWith('http') ? avatar : `/api${avatar}`) : '';
  } else {
    // 普通用户看到服务人员头像
    const avatar = session.staff?.user?.avatar
    return avatar ? (avatar.startsWith('http') ? avatar : `/api${avatar}`) : '';
  }
}

const formatTime = (time) => {
  return formatDate(time, 'HH:mm')
}

// WebSocket连接
const connectWebSocket = () => {
    if (ws.value?.readyState === WebSocket.OPEN) {
        console.log('WebSocket已经连接')
        return
    }

    console.log("连接WebSocket，用户ID:", userId.value)
    const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
    const wsUrl = `${wsProtocol}//${window.location.hostname}:1234/websocket/chat/${userId.value}`

    try {
        ws.value = new WebSocket(wsUrl)
        
        ws.value.onopen = () => {
            console.log('WebSocket连接已建立，用户ID:', userId.value)
            if (pendingMessage.value) {
                sendMessage()
            }
        }
        
        ws.value.onmessage = (event) => {
            console.log('收到WebSocket原始消息:', event.data)
            try {
                const message = JSON.parse(event.data)
                console.log('解析后的WebSocket消息:', message)
                handleWebSocketMessage(message)
            } catch (error) {
                console.error('解析WebSocket消息失败:', error)
            }
        }
        
        ws.value.onclose = (event) => {
            console.log('WebSocket连接已关闭', event.code, event.reason)
            // 如果不是正常关闭，尝试重新连接
            if (event.code !== 1000) {
                console.log('WebSocket异常关闭，3秒后尝试重新连接')
                setTimeout(() => {
                    console.log('尝试重新连接WebSocket')
                    connectWebSocket()
                }, 3000)
            }
        }
        
        ws.value.onerror = (error) => {
            console.error('WebSocket连接错误:', error)
            ElMessage.error('聊天连接失败，请刷新页面重试')
        }
    } catch (error) {
        console.error('创建WebSocket连接失败:', error)
        ElMessage.error('创建聊天连接失败，请刷新页面重试')
    }
}

// 添加一个变量来存储待发送的消息
const pendingMessage = ref('')

// 加载会话列表
const loadSessions = async () => {
  try {
    const params = {
      userId: userId.value,
      pageNum: 1,
      pageSize: 20
    }
    await request.get('/chat/sessions', params, {
      showDefaultMsg: false,
      onSuccess: (data) => {
        // 不再过滤 lastMessage 为空的会话，防止死循环创建
        sessions.value = data.records || []
        // 如果指定了目标ID,选择对应会话
        if (props.targetId) {
          const targetSession = sessions.value.find(s => 
            userStore.userInfo?.roleCode === 'STAFF' 
              ? s.userId === props.targetId
              : s.staffId === props.targetId
          )
          if (targetSession) {
            selectSession(targetSession)
          } else {
            // 如果没有找到对应会话，但有targetId，创建新会话
            createNewSession()
          }
        } else if (sessions.value.length > 0) {
          selectSession(sessions.value[0])
        }
      },
      onError: (error) => {
        console.error('加载会话列表失败:', error)
      }
    })
  } catch (error) {
    console.error('加载会话列表失败:', error)
  }
}

// 加载聊天记录
const loadMessages = async (sessionId) => {
  try {
    console.log('加载会话消息，会话ID:', sessionId)
    await request.get('/chat/messages', {
      sessionId: sessionId,
      pageNum: 1,
      pageSize: 1000  // 增加分页大小，确保获取所有消息
    }, {
      showDefaultMsg: false,
      onSuccess: (data) => {
        console.log('加载到消息数量:', data.records?.length || 0)
        // 保持消息顺序，不进行反转
        messages.value = data.records || []
        nextTick(() => {
          scrollToBottom()
        })
      },
      onError: (error) => {
        console.error('加载聊天记录失败:', error)
      }
    })
  } catch (error) {
    console.error('加载聊天记录失败:', error)
  }
}

// 选择会话
const selectSession = async (session) => {
  console.log('选择会话:', session)
  currentSession.value = session
  await loadMessages(session.id)
  // 标记消息为已读
  if (session.unreadCount > 0) {
    await markMessagesAsRead(session.id)
  }
  // 更新导航栏未读消息数
  updateNavbarUnreadCount()
}

// 更新导航栏未读消息数
const updateNavbarUnreadCount = () => {
  // 计算总未读消息数
  const totalUnread = sessions.value.reduce((total, s) => {
    // 只计算不是自己发送的消息的未读数量，且不在当前会话
    if (s.unreadCount > 0 && s.lastSenderId !== userId.value && s.id !== currentSession.value?.id) {
      return total + s.unreadCount
    }
    return total
  }, 0)

  // 通知导航栏更新未读消息数量
  document.dispatchEvent(new CustomEvent('update-unread-count', {
    detail: { unreadCount: totalUnread }
  }))
}

// 确认清空聊天记录
const confirmClearMessages = () => {
  if (!currentSession.value) return
  
  ElMessageBox.confirm(
    '确定要清空所有聊天记录吗？此操作不可恢复。',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    clearMessages()
  }).catch(() => {
    // 用户取消操作
  })
}

// 清空聊天记录
const clearMessages = async () => {
    if (!currentSession.value) return
    try {
        await request.delete(`/chat/sessions/${currentSession.value.id}/messages`, null, {
            successMsg: '聊天记录已清空',
            onSuccess: () => {
                console.log('清空聊天记录成功')
                // 从会话列表中移除当前会话
                sessions.value = sessions.value.filter(s => s.id !== currentSession.value.id)
                // 清空当前会话和消息
                currentSession.value = null
                messages.value = []
                // 强制更新界面
                nextTick(() => {
                    // 触发会话列表更新
                    document.dispatchEvent(new CustomEvent('update-unread-count', {
                        detail: { unreadCount: 0 }
                    }))
                })
            }
        })
    } catch (error) {
        console.error('清空聊天记录失败:', error)
    }
}

// 处理消息清空
const handleMessagesCleared = (message) => {
    console.log('处理消息清空:', message)
    // 如果是当前会话的消息被清空，立即更新界面
    if (currentSession.value && currentSession.value.id === message.sessionId) {
        console.log('清空当前会话消息')
        // 从会话列表中移除当前会话
        sessions.value = sessions.value.filter(s => s.id !== message.sessionId)
        // 清空当前会话和消息
        currentSession.value = null
        messages.value = []
    } else {
        console.log('更新非当前会话')
        // 即使不是当前会话，也要从会话列表中移除
        sessions.value = sessions.value.filter(s => s.id !== message.sessionId)
    }
}

// 处理WebSocket消息
const handleWebSocketMessage = (message) => {
    console.log('处理WebSocket消息:', message)
    
    // 检查消息类型
    if (message.type === 'message' || (message.content && message.senderId && message.receiverId)) {
        handleNewMessage(message)
    } else if (message.type === 'message_deleted') {
        handleMessageDeleted(message)
    } else if (message.type === 'messages_cleared' || (message.type === 'session_update' && !message.lastMessage)) {
        console.log('收到消息清空通知:', message)
        handleMessagesCleared(message)
    } else if (message.type === 'session_update') {
        handleSessionUpdate(message)
    } else if (message.type === 'message_read') {
        handleMessageRead(message)
    } else {
        console.log('未知类型的WebSocket消息:', message)
    }
}

// 处理新消息
const handleNewMessage = (message) => {
    console.log('处理新消息:', message)
    // 优先查找本地临时消息并替换
    const tempIndex = messages.value.findIndex(
        msg => msg.tempId && msg.content === message.content && msg.senderId === message.senderId
    )
    if (tempIndex !== -1) {
        // 用后端消息替换本地临时消息
        messages.value.splice(tempIndex, 1, message)
        return
    }
    // 检查消息是否已存在
    const messageExists = messages.value.some(msg => msg.id === message.id)
    if (!messageExists) {
        console.log('消息不存在，准备添加到消息列表')
        // 如果是当前会话的消息，直接添加到消息列表
        if (currentSession.value?.id === message.sessionId) {
            console.log('当前会话收到新消息，添加到消息列表')
            messages.value = [...messages.value, message]
            nextTick(() => {
                scrollToBottom()
            })
                // 标记消息为已读
            markMessagesAsRead(message.sessionId)
        } else {
            console.log('非当前会话收到新消息')
        }

        // 更新会话信息
        const sessionIndex = sessions.value.findIndex(s => s.id === message.sessionId)
        if (sessionIndex !== -1) {
            console.log('更新会话信息')
            // 创建新的会话对象
            const updatedSession = {
                ...sessions.value[sessionIndex],
                lastMessage: message.content,
                lastSenderId: message.senderId,
                updateTime: message.createTime
            }
            
            // 如果不是当前会话且是接收到的消息，增加未读计数
            if (currentSession.value?.id !== message.sessionId && message.senderId !== userId.value) {
                updatedSession.unreadCount = (updatedSession.unreadCount || 0) + 1
            }
            
            // 更新会话列表
            const newSessions = [...sessions.value]
            newSessions.splice(sessionIndex, 1)
            newSessions.unshift(updatedSession)
            sessions.value = newSessions
            
            // 如果是当前会话，更新当前会话显示
            if (currentSession.value?.id === message.sessionId) {
                console.log('更新当前会话显示')
                currentSession.value = updatedSession
            }
        } else {
            console.log('未找到对应的会话')
        }
    } else {
        console.log('消息已存在，跳过处理')
    }
}

// 处理消息删除
const handleMessageDeleted = (message) => {
    console.log('处理消息删除:', message)
    // 从本地消息列表中移除被删除的消息
    messages.value = messages.value.filter(msg => msg.id !== message.messageId)
    
    // 如果删除的是当前会话的消息，需要更新会话信息
    if (currentSession.value && currentSession.value.id === message.sessionId) {
        const sessionIndex = sessions.value.findIndex(s => s.id === message.sessionId)
        if (sessionIndex !== -1) {
            const updatedSession = { ...sessions.value[sessionIndex] }
            
            if (messages.value.length > 0) {
                const lastMessage = messages.value[messages.value.length - 1]
                updatedSession.lastMessage = lastMessage.content
                updatedSession.lastSenderId = lastMessage.senderId
                updatedSession.updateTime = lastMessage.createTime
            } else {
                updatedSession.lastMessage = ''
                updatedSession.lastSenderId = null
                updatedSession.updateTime = new Date().toISOString()
            }
            
            // 更新会话列表
            const newSessions = [...sessions.value]
            newSessions[sessionIndex] = updatedSession
            sessions.value = newSessions
            
                // 更新当前会话显示
            currentSession.value = updatedSession
        }
    }
}

// 处理会话更新
const handleSessionUpdate = (message) => {
    console.log('处理会话更新:', message)
    const sessionIndex = sessions.value.findIndex(s => s.id === message.sessionId)
    if (sessionIndex !== -1) {
        const updatedSession = {
            ...sessions.value[sessionIndex],
            lastMessage: message.lastMessage,
            lastSenderId: message.lastSenderId,
            updateTime: message.updateTime,
            unreadCount: message.unreadCount
        }
        
        // 更新会话列表
        const newSessions = [...sessions.value]
        newSessions.splice(sessionIndex, 1)
        newSessions.unshift(updatedSession)
        sessions.value = newSessions
        
        // 如果是当前会话，更新显示
        if (currentSession.value?.id === message.sessionId) {
            currentSession.value = updatedSession
        }
    }
}

// 处理消息已读通知
const handleMessageRead = (message) => {
    console.log('收到消息已读通知:', message)
    const sessionIndex = sessions.value.findIndex(s => s.id === message.sessionId)
    if (sessionIndex !== -1) {
        const updatedSession = {
            ...sessions.value[sessionIndex],
            unreadCount: 0
        }
        // 更新会话列表
        const newSessions = [...sessions.value]
        newSessions[sessionIndex] = updatedSession
        sessions.value = newSessions
        
        // 如果是当前会话，更新显示
        if (currentSession.value?.id === message.sessionId) {
            currentSession.value = updatedSession
        }
    }
}

// 发送消息
const sendMessage = async () => {
    if (!inputMessage.value?.trim()) {
        return
    }
    // 检查是否有当前会话
    if (!currentSession.value) {
        ElMessage.warning('请先选择聊天对象')
        return
    }
    const content = inputMessage.value.trim()
    try {
        // 通过HTTP接口发送消息，拿到真实id
        const res = await request.post('/chat/messages/send', {
            senderId: userId.value,
            receiverId: userStore.userInfo?.roleCode === 'STAFF' 
                ? currentSession.value?.userId
                : currentSession.value?.staff?.userId,
            content: content
        }, { showDefaultMsg: false })
        if (res && res.id) {
            // 用真实id渲染消息
            const realMsg = {
                ...res,
                sessionId: currentSession.value.id
            }
            messages.value = [...messages.value, realMsg]
            // 更新会话信息
            const sessionIndex = sessions.value.findIndex(s => s.id === currentSession.value.id)
            if (sessionIndex !== -1) {
                const updatedSession = {
                    ...sessions.value[sessionIndex],
                    lastMessage: content,
                    lastSenderId: userId.value,
                    updateTime: new Date().toISOString()
                }
                const newSessions = [...sessions.value]
                newSessions.splice(sessionIndex, 1)
                newSessions.unshift(updatedSession)
                sessions.value = newSessions
                currentSession.value = updatedSession
            }
            nextTick(() => {
                scrollToBottom()
            })
            inputMessage.value = ''
            pendingMessage.value = ''
        }
    } catch (error) {
        console.error('发送消息失败:', error)
        ElMessage.error('发送消息失败，请重试')
    }
}

// 标记消息为已读
const markMessagesAsRead = async (sessionId) => {
  try {
    console.log('标记消息为已读:', sessionId)
    await request.post(`/chat/messages/read?sessionId=${sessionId}&userId=${userId.value}`, null, {
      showDefaultMsg: false,
      onSuccess: () => {
        console.log('消息已标记为已读')
        // 更新会话列表中的未读消息数
        const session = sessions.value.find(s => s.id === sessionId)
        if (session) {
          session.unreadCount = 0
          // 如果当前正在查看该会话，更新当前会话显示
          if (currentSession.value?.id === sessionId) {
            currentSession.value = { ...session }
          }
        }
        
        // 更新导航栏未读消息数
        updateNavbarUnreadCount()
      }
    })
  } catch (error) {
    console.error('标记消息已读失败:', error)
  }
}

// 滚动到底部
const scrollToBottom = () => {
  const container = messageList.value?.querySelector('.el-scrollbar__wrap')
  if (container) {
    container.scrollTop = container.scrollHeight
  }
}

// 创建新会话
const createNewSession = async () => {
  try {
    const data = {
      userId: userStore.userInfo?.roleCode === 'STAFF' ? props.targetId : userId.value,
      staffId: userStore.userInfo?.roleCode === 'STAFF' ? userId.value : props.targetId
    }
    console.log("创建会话参数:", data)
    await request.post('/chat/sessions?userId=' + userId.value + '&staffId=' + props.targetId, null, {
      showDefaultMsg: false,
      onSuccess: () => {
        // 创建成功后重新加载会话列表
        loadSessions()
      },
      onError: (error) => {
        console.error('创建会话失败:', error)
        ElMessage.error('创建会话失败')
      }
    })
  } catch (error) {
    console.error('创建会话失败:', error)
  }
}

// 删除单条消息
const deleteMessage = async (messageId) => {
  try {
    console.log('开始删除消息:', messageId)
    await request.delete(`/chat/messages/${messageId}`, null, {
      showDefaultMsg: false,
      onSuccess: () => {
        console.log('删除消息成功:', messageId)
        // 从本地消息列表中移除
        messages.value = messages.value.filter(msg => msg.id !== messageId)
        
        // 更新会话列表中的最后一条消息
        if (currentSession.value) {
          const session = sessions.value.find(s => s.id === currentSession.value.id)
          if (session) {
            // 如果删除的是最后一条消息，需要更新会话的最后一条消息
            if (messages.value.length > 0) {
              // 找到新的最后一条消息
              const lastMessage = messages.value[messages.value.length - 1]
              session.lastMessage = lastMessage.content
              session.lastSenderId = lastMessage.senderId
              session.updateTime = lastMessage.createTime
            } else {
              // 如果没有消息了，清空最后一条消息
              session.lastMessage = ''
              session.lastSenderId = null
            }
            
            // 更新当前会话的显示
            currentSession.value = { ...session }
          }
        }
      },
      onError: (error) => {
        console.error('删除消息失败:', error)
        ElMessage.error('删除消息失败')
      }
    })
  } catch (error) {
    console.error('删除消息失败:', error)
    ElMessage.error('删除消息失败')
  }
}

// 删除会话
const deleteSession = async (sessionId) => {
  try {
    await request.delete(`/chat/sessions/${sessionId}`, null, {
      successMsg: '会话已删除',
      onSuccess: () => {
        // 从会话列表中移除
        sessions.value = sessions.value.filter(s => s.id !== sessionId)
        
        // 如果删除的是当前会话，则清空当前会话和消息
        if (currentSession.value && currentSession.value.id === sessionId) {
          currentSession.value = null
          messages.value = []
        }
      }
    })
  } catch (error) {
    console.error('删除会话失败:', error)
  }
}

// 获取消息状态
const getMessageStatus = (session) => {
  // 如果最后发送者是当前用户，显示已读/未读状态
  if (session.lastSenderId === userId.value) {
    return session.unreadCount > 0 ? '未读' : '已读';
  }
  return '';
}

// 生命周期钩子
onMounted(async () => {
    console.log('组件挂载，用户ID:', userId.value)
    if (dialogVisible.value) {
        console.log('对话框已打开，加载会话列表并连接WebSocket')
        await loadSessions()
        connectWebSocket()
    }
})

onUnmounted(() => {
    console.log('组件卸载，关闭WebSocket连接')
    if (ws.value) {
        ws.value.close()
    }
})

// 监听对话框显示状态
watch(dialogVisible, async (val) => {
    if (val) {
        console.log('对话框打开，加载会话列表并连接WebSocket')
        await loadSessions()
        connectWebSocket()
    } else {
        console.log('对话框关闭，更新导航栏未读消息数')
        // 关闭对话框时更新导航栏未读消息数
        updateNavbarUnreadCount()
    }
})

// 监听当前会话变化
watch(currentSession, async (newSession) => {
  if (newSession && newSession.unreadCount > 0) {
    await markMessagesAsRead(newSession.id)
  }
  // 更新导航栏未读消息数
  updateNavbarUnreadCount()
})
</script>

<style lang="scss" scoped>
.chat-dialog {
  :deep(.el-dialog__body) {
    padding: 0;
  }
}

.chat-container {
  display: flex;
  height: 600px;
  
  .session-list {
    width: 280px;
    border-right: 1px solid #e0e0e0;
    display: flex;
    flex-direction: column;
    
    .session-header {
      padding: 15px;
      border-bottom: 1px solid #e0e0e0;
      
      h3 {
        margin: 0;
        font-size: 16px;
      }
    }
    
    .session-item {
      display: flex;
      align-items: flex-start;
      justify-content: space-between;
      padding: 12px;
      cursor: pointer;
      transition: all 0.3s;
      
      &:hover {
        background-color: #f5f7fa;
      }
      
      &.active {
        background-color: #ecf5ff;
      }
      
      &.has-unread {
        background-color: rgba(64, 158, 255, 0.05);
        
        .session-info {
          .session-name {
            font-weight: 500;
            color: #303133;
          }
          
          .last-message {
            color: #606266;
          }
        }
      }
      
      .session-content {
        display: flex;
        align-items: flex-start;
        flex: 1;
      }
      
      .session-actions {
        opacity: 0;
        transition: opacity 0.3s;
        
        .delete-icon {
          color: #909399;
          cursor: pointer;
          margin-left: 8px;
          font-size: 16px;
          transition: color 0.3s;
        }
          
        .delete-icon:hover {
            color: #f56c6c;
        }
      }
      
      &:hover .session-actions {
        opacity: 1;
      }
      
      .session-info {
        flex: 1;
        margin-left: 12px;
        overflow: hidden;
        
        .session-name {
          font-size: 14px;
          margin-bottom: 4px;
          display: flex;
          align-items: center;
          
          .unread-indicator {
            display: inline-block;
            width: 6px;
            height: 6px;
            border-radius: 50%;
            background-color: var(--el-color-primary);
            margin-left: 5px;
          }
        }
        
        .last-message {
          font-size: 12px;
          color: #909399;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          text-align: left;
        }
      }
      
      .unread-badge {
        margin-left: 8px;
        
        :deep(.el-badge__content) {
          background-color: var(--el-color-primary);
          border: none;
          padding: 0 6px;
          height: 18px;
          line-height: 18px;
          border-radius: 9px;
          font-size: 12px;
        }
      }
    }
  }
  
  .chat-main {
    flex: 1;
    display: flex;
    flex-direction: column;
    
    .chat-header {
      padding: 15px;
      border-bottom: 1px solid #e0e0e0;
      font-size: 16px;
      font-weight: 500;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .message-list {
      flex: 1;
      padding: 20px;
      overflow-y: auto;
      
      .message-item {
        display: flex;
        margin-bottom: 20px;
        
        &.message-mine {
          flex-direction: row-reverse;
          
          .message-content {
            margin-left: 0;
            margin-right: 12px;
            
            .message-text {
              background-color: #95ec69;
            }
          }
        }
        
        .message-content {
          margin-left: 12px;
          max-width: 70%;
          
          .message-text {
            padding: 10px 15px;
            background-color: #f5f5f5;
            border-radius: 4px;
            word-break: break-all;
          }
          
          .message-time {
            display: flex;
            align-items: center;
            justify-content: space-between;
            font-size: 12px;
            color: #909399;
            margin-top: 4px;
            
            .read-status {
              font-size: 12px;
              color: #909399;
              margin-left: 5px;
            }
            
            .delete-icon {
              color: #909399;
              cursor: pointer;
              margin-left: 8px;
              font-size: 16px;
              transition: color 0.3s;
            }
            
            .delete-icon:hover {
                color: #f56c6c;
            }
          }
        }
      }
    }
    
    .chat-input {
      padding: 15px;
      border-top: 1px solid #e0e0e0;
      display: flex;
      align-items: flex-end;
      gap: 10px;
      
      .el-input {
        flex: 1;
      }
      
      .el-button {
        height: 32px;
      }
    }
  }
}
</style> 